package thread;
import handlers.BidirectionalConnectionHandler;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ProxyTCPConcurrentServer {
	
	  
    public ProxyTCPConcurrentServer(final int port, final InetAddress interfaz, 
    		final int portdestiny, final String ipaddress, final BidirectionalConnectionHandler handler)

            throws IOException {
        final ServerSocket server = new ServerSocket(port, 50, interfaz);

        System.out.printf("Escuchando en %s\n", server.getLocalSocketAddress());
        final Executor executor = Executors.newFixedThreadPool(5); 
        
        while (true) {
        	final Socket socket = server.accept(); 
        	executor.execute(new Runnable() {
    	        public void run() {
    	        	try {
    	        		String s = socket.getRemoteSocketAddress().toString();
    	        		System.out.printf("Se conecto %s\n", s);
    	        		Socket s2= new Socket(ipaddress, portdestiny);
    	        		System.out.printf("Conexión PROXY con %s : %d\n", ipaddress, portdestiny);
						handler.handle(socket,s2);
						
					} catch (IOException e) {
						System.out.println("No se pudo conectar con el puerto remoto");
//						throw new RuntimeException(e);
					} finally {
						try {
							if (!socket.isClosed()) {
								socket.close();
								System.out.printf("Terminando\n");
							}
						} catch (IOException e) {
//							throw new RuntimeException(e);
						}
					}
    	        }
    	    });

        }
    }
}
